package chapter23;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/27 15:06
 */
public class GeneralProxyDemo {
    private static <T> T getProxy(Class<T> intf, T realObj) {
        return (T) Proxy.newProxyInstance(intf.getClassLoader(), new Class[]{intf}, new SimpleInvoationHandler(realObj));
    }

    public static void main(String[] args) {
        IServiceA serviceA = new ServiceAImpl();
        IServiceA proxyA = getProxy(IServiceA.class, serviceA);
        proxyA.sayHello();

        IServiceB serviceB = new ServiceBImpl();
        IServiceB proxyB = getProxy(IServiceB.class, serviceB);
        proxyB.fly();

    }

    static interface IServiceA {
        public void sayHello();
    }

    static interface IServiceB {
        public void fly();
    }

    static class ServiceAImpl implements IServiceA {
        @Override
        public void sayHello() {
            System.out.println("hello");
        }
    }

    static class ServiceBImpl implements IServiceB {
        @Override
        public void fly() {
            System.out.println("flying");
        }
    }

    static class SimpleInvoationHandler implements InvocationHandler {
        private Object realObj;

        public SimpleInvoationHandler(Object realObj) {
            this.realObj = realObj;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("entering " + method.getName());
            Object result = method.invoke(realObj, args);
            System.out.println("leaving " + method.getName());
            return result;
        }
    }

}
